package model

import (
	"errors"
	"gorm.io/gorm"
	"shop/database/mysql"
)

// 商品表
type Goods struct {
	gorm.Model
	Title       string `gorm:"column:title;type:varchar(100);not null"  json:"title"`
	TypesId     int64  `gorm:"type:int(11);comment:商品分类ID" json:"types-id"`
	Description string `gorm:"column:description;type:varchar(255);comment:商品描述" json:"description"`
	Img         string `gorm:"column:img;type:json" json:"img"`
}

func (g *Goods) GoodsListById(Id int64) (info *Goods, err error) {
	return info, mysql.WithMysql(func(db *gorm.DB) error {
		err = db.Model(g).Where("id = ?", Id).First(&info).Error
		if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}
		return nil
	})
}

func (g *Goods) GoodsSearchByGoodsTitle(title string, page, pageSize int, typesIDs []int64) (info []*Goods, err error) {
	return info, mysql.WithMysql(func(db *gorm.DB) error {
		query := db.Model(g)
		query = query.Where("title = ?", title)

		if typesIDs != nil {
			query = query.Where("types_id in (?)", typesIDs)
		}
		offset := (page - 1) * pageSize
		return db.Limit(pageSize).Offset(offset).Find(&info).Error
	})
}

func (g *Goods) GoodsListByIds(Ids []uint) (info []*Goods, err error) {
	return info, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(g).Where("id in (?)", Ids).Find(&info).Error
	})
}
